import { createSlice } from "@reduxjs/toolkit";
import type { PayloadAction } from "@reduxjs/toolkit";

// 导入 Answer 类型，用于类型检查
import type { Answer } from '../index.ts';

// 定义状态接口，明确每个字段的类型
interface QuestionState {
    questions: any[];       // 存储所有问题
    answersId: number[];    // 存储用户选择的答案ID
    score: number;          // 存储用户得分
}

// 初始状态
const initialState: QuestionState = {
    questions: [],
    answersId: [],
    score: 0
};

// 创建问题相关的 Redux slice
const questional = createSlice({
    name: 'questional',  // slice 名称
    initialState,        // 初始状态
    reducers: {          // 定义 reducer 函数

        // 设置问题列表
        setQuestions(state, action: PayloadAction<any[]>) {
            state.questions = action.payload;  // 将问题列表存入状态
        },

        // 添加用户选择的答案ID
        setAnswersId(state, action: PayloadAction<number>) {
            state.answersId.push(action.payload);  // 将答案ID添加到数组中
        },

        // 计算正确答案并更新分数
        findrigthAnswer(state, action: PayloadAction<(Answer | undefined)[]>) {
            state.score = 0;  // 重置分数为0

            // 遍历所有用户答案
            state.answersId.forEach((userAnswerId, index) => {
                // 获取当前题目的正确答案
                const correctAnswer = action.payload[index];

                // 如果存在正确答案且用户答案匹配
                if (correctAnswer && userAnswerId === correctAnswer.topic_answer_id) {
                    // 计算每题的分值并累加到总分
                    state.score += 100 / state.answersId.length;
                }
            });
        }
    }
});

// 导出 reducer 函数
export default questional.reducer;

// 导出 action creators
export const { setQuestions, setAnswersId, findrigthAnswer } = questional.actions;